<!--
 * @Description: 
 * @Version: 1.0.0
 * @Autor: 
 * @Date: 2020-08-11 10:57:41
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-01 23:32:36
-->
<template>
	<view style="height: 100vh; display: flex; flex-direction: column">
		<view class="container">
			<view style="display: flex; justify-content: space-between; padding-top: 12px">
				<view style="display: flex; align-items: center; color: white">
					<u-button type="text" @click="sizeShow = true" size="small"
						style="margin-right: 24px">模板导入</u-button>
					<u-button type="text" size="small" @click="saveShow = true">存为模板</u-button>
				</view>
				<u-button style="flex-grow: 0; width: 64px; margin: 0" type="primary" size="small"
					@click="creatPoster('同步')">同步</u-button>
			</view>
			<view class="content" id="content" :style="{
          backgroundColor: dragBg.bgColor,
          flex:'1'
        }" @click="handleClick">
				<!-- 删除全部 -->
				<image v-show="!saveStatus" class="del-icon" @click="handleCanvasCancel"
					:src="require('./static/s-poster/del-ll.png')" alt="" srcset=""></image>
				<!-- #ifndef H5 -->
				<s-color :dragBg="dragBg" ref="colorTheme" :cover="cover" :hasBg="true" :is-show="colorShow"
					@confirm.stop="handleColorConfirm" @cancel="colorShow = false" />
				<!-- #endif -->
				<s-template :is-show="sizeShow" @confirm="onConfirm" :tempList="tempList"
					@cancel="sizeShow = false"></s-template>
				<s-color ref="colorTheme" :dragBg="dragBg" :hasBg="true" :cover="cover" :is-show="colorShow"
					@confirm="handleColorConfirm" @cancel="colorShow = false" />
				<image class="bg-img" :style="{
            left: dragBg.left + 'px',
            top: dragBg.top + 'px',
            borderRadius: dragBg.radius + 'px',
          }" :mode="mode" v-if="dragBg.url" :src="dragBg.fileUrl" alt="" srcset="" />
				<view class="drag-wrap" v-for="(item, i) in dragList" :key="item.id"
					:style="{ '--border-color': borderColor }" @click.stop="handleClickStart($event, item.id)">
					<!-- 拖拽元素 -->
					<!-- 图片 -->
					<view v-if="item.type === 'img'">
						<img @touchstart.stop="handleTouchStart" @touchmove.stop="handleTouchMove"
							@touchend.stop="handleTouchEnd" :data-id="item.id" :style="{
                top: item.top + 'px',
                left: item.left + 'px',
                width: item.width + 'px',
                height: item.height + 'px',
                transform: 'rotate(' + item.rotate + 'deg)',
                borderRadius: item.radius + 'px',
              }" class="drag-item" :class="{ active: item.active }" :src="item.fileUrl" alt="" srcset="" />
					</view>
					<!-- 形状 -->
					<view v-if="item.type === 'shape'">
						<view @touchstart.stop="handleTouchStart" @touchmove.stop="handleTouchMove"
							@touchend.stop="handleTouchEnd" :data-id="item.id" :style="{
                top: item.top + 'px',
                left: item.left + 'px',
                width: item.width + 'px',
                height: item.height + 'px',
                transform: 'rotate(' + item.rotate + 'deg)',
                borderWidth: item.borderWidth + 'px',
                borderColor: item.borderColor,
                backgroundColor: item.backgroundColor,
                borderStyle: item.borderStyle,
                borderRadius: item.radius + 'px',
                boxSizing: 'content-box',
              }" class="drag-item" :class="{ active: item.active }" :src="item.url" alt="" srcset=""></view>
					</view>
					<!-- 文本 -->
					<view v-if="item.type === 'text'">
						<text class="drag-item" @touchstart.stop="handleTouchStart" @touchmove.stop="handleTouchMove"
							@touchend.stop="handleTouchEnd" :data-id="item.id" :class="{ active: item.active }" :style="{
                top: item.top + 'px',
                left: item.left + 'px',
                width: item.width + 'px',
                height: item.height + 'px',
                transform: 'rotate(' + item.rotate + 'deg)',
                color: item.color,
                fontSize: item.fontSize + 'px' || 15 + 'px',
                textDecoration: item.textDecoration,
                textAlign: item.textAlign,
                fontWeight: item.fontWeight,
                fontFamily: item.fontFamily,
              }">
							{{ item.text }}
						</text>
					</view>
					<!-- 编辑 -->
					<img class="scale-icon" v-show="item.active" @click="handleEdit(item, i)" :data-id="item.id"
						:style="{ top: item.top - 10 + 'px', left: item.left - 10 + 'px' }"
						:src="require('./static/s-poster/edit.png')" alt="" srcset="" />
					<!-- 缩放 -->
					<view @touchstart.stop="handleScaleStart" @touchmove.stop="handleScaleMove" :style="{
              top: item.height - 0 + item.top - 18 + 'px',
              left: item.width - 0 + item.left - 18 + 'px',
              padding: '10px',
              boxShadow: 'none',
              background: 'none',
            }" :data-id="item.id" class="scale-icon" v-show="item.active">
						<img style="width: 100%; box-shadow: 0 0 4px #000; border-radius: 50%"
							:src="require('./static/s-poster/scale_icon.png')" alt="" srcset="" />
					</view>

					<img class="scale-icon" v-show="item.active" @click="handleDel(i)" :data-id="item.id" :style="{
              top: item.top - 10 + 'px',
              left: item.width - 0 + item.left - 5 + 'px',
            }" :src="require('./static/s-poster/del_1.png')" alt="" srcset="" />
				</view>
				<s-font ref="font" :is-show="fontShow" :fontData="font" @cancel="fontShow = false"
					@confirm="handleFontConfirm" />
				<s-shape ref="shape" :is-show="shapeShow" :shapeData="shapeData" @cancel="shapeShow = false"
					@confirm="handleShapeConfirm" />
				<s-img ref="imgObj" :imgObjData="imgObjData" @confirm="handleImgConfirm" />
				<s-bg @confirm="handleBgConfirm" :is-show="bgShow" @cancel="bgShow = false" ref="Sbg"
					@openImage="handleChoose('bg')"></s-bg>
				<u-modal :show="saveShow" width="300px" showCancelButton title="模板名称"
					@cancel="(saveShow = false), (textValue = '')" @confirm="saveTemplate">
					<u--input placeholder="请输入模板名称" border="surround" v-model="textValue"></u--input>
				</u-modal>
			</view>
		</view>
		<view class="toolbar">
			<view @click="onClick(item)" class="toolbar_item" v-for="item in toolbarList">
				<image class="toolbar_icon" :src="item.url"></image>
				<text class="toolbar_text">{{ item.text }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	import sFont from "./components/s-font/s-font1.vue";
	import sShape from "./components/s-shape/s-shape1.vue";
	import sImg from "./components/s-img/s-img.vue";
	import sBg from "./components/s-bg/index.vue";
	import sColor from "./components/s-color/s-color.vue";
	import sTemplate from "./components/s-template/index.vue";
	import {
		store
	} from "../../../../main";
	import {
		upload,
		chooseImgUpload,
		add,
		get
	} from "./utils/apiFunc";

	import {
		getSystem
	} from "./utils";
	import throttle from "./utils/throttle.js";
	import html2canvas from "html2canvas";
	export default {
		components: {
			sFont,
			sColor,
			sShape,
			sImg,
			sBg,
			sTemplate,
		},
		props: {
			dataSource: {
				type: Object,
				default () {
					return {
						dragBg: {},
						dragList: [],
					};
				},
			},
		},
		data() {
			return {
				colorShow: false,
				bgShow: false,
				sizeShow: false,
				saveStatus: false,
				toolbarList: [{
						text: "矩形",
						url: require("./static/toolbar/rect.png"),
						onClick: () => {
							this.shapeShow = true;
						},
					},
					{
						text: "文字",
						url: require("./static/toolbar/type.png"),
						onClick: () => {
							this.font = {};
							this.fontShow = true;
							this.$refs.font.active = 0;
						},
					},
					{
						text: "图片",
						url: require("./static/toolbar/image.png"),
						onClick: () => {
							let zIndex = this.dragList.length + 1;
							this.handleChoose("pic");
							this.imgObjData = {
								zIndex,
							};
						},
					},
					{
						text: "背景",
						url: require("./static/toolbar/bg.png"),
						onClick: () => {
							this.bgShow = true;
						},
					},
				],
				cover: false,
				mode: "widthFix",
				system: {},
				canvasToImgUrl: "",
				font: {},
				shapeData: {},
				imgObjData: {},
				fontSize: 10,
				fontShow: false,
				shapeShow: false,
				textValue: "", //输入文本
				showDiolag: false, //背景图选择弹窗
				showTempDiolag: false, //模板选择弹窗
				showTextDiolag: false, //文本输入框弹窗
				index: 0,
				canvasShow: false,
				dragBg: {
					bgColor: "#6739b6",
					color: "#6739b6",
					url: "",
					width: 0,
					height: 0,
					top: 0,
					left: 0,
					radius: 0,
					cover: false,
				},
				isEdit: false,
				currentIndex: "",
				beforeMove: {},
				afterMove: {},
				dragList: [],
				saveShow: false,
				textValue: "",
				tempList: [],
			};
		},
		computed: {
			borderColor() {
				let whitelist = [
					"#FFFFFF",
					"transparent",
					"#ECECFF",
					"#D2E9FF",
					"#ECFFFF",
					"#FFFFCE ",
					"#FFF4C1",
					"#F5FFE8",
					"#FFFFF4",
					"#FFFCEC",
					"#FFFAF4",
					"#FFF3EE",
					"#F2E6E6",
					"#E8E8D0",
					"#D1E9E9",
					"#F3F3FA",
				];
				if (whitelist.includes(this.dragBg.bgColor)) {
					return "#000";
				} else {
					return "#fff";
				}
			},
		},
		mounted() {
			this.system = getSystem();
			window.addEventListener("newSetItemEvent", (e) => {
				// doSomething
				// 回调的e对象中含有localStorage改变的键key和新旧值newValue/oldValue及一些其他属性
				this.tempList = JSON.parse(e.newValue);
				window.ReactNativeWebView.postMessage("模板" + e.newValue);
			});
			// this.tempList = localStorage.getItem("dragData")
			//   ? JSON.parse(localStorage.getItem("dragData"))
			//   : [];
			const handleMessage = (event) => {
				const message = event.data;
				const data = JSON.parse(message);
				if (data.index >= 0) {
					this.tempList = data.data;
					this.dragList = data.data[data.index].value.dragList;
					this.dragBg = data.data[data.index].value.dragBg;
					localStorage.setItem(JSON.stringify(data.data));
				} else {
					this.tempList = data;
					localStorage.setItem(message);
				}
			};
			document.addEventListener("message", handleMessage);
			window.addEventListener('message',handleMessage)
		},
		watch: {
			dataSource: {
				handler(val) {
					if (val) {
						this.dragBg = val.dragBg || {};
						this.dragBg.cover = this.dragBg.cover;
					}
				},
				deep: true,
				immediate: true,
			},
			"dragBg.cover": {
				handler(val) {
					this.getMode();
				},
				deep: true,
				immediate: true,
			},
		},
		methods: {
			// toolbar onclick
			onClick(item) {
				item.onClick();
			},
			handleBgConfirm(value) {
				this.bgShow = false;
				store.commit("setBgColor", value);
			},
			throttle() {
				throttle(this.creatPoster, 1500);
			},
			change() {
				this.$refs.colorTheme.show = true;
			},
			handleColorConfirm(data) {
				this.dragBg.bgColor = data.bgColor;
				this.dragBg.url = data.url;
				this.colorShow = false;
				this.dragBg.cover = data.cover;
				if (data.url) {
					uni.getImageInfo({
						src: data.url,
						success: (res) => {
							let {
								height,
								width
							} = res;
							let {
								h,
								w
							} = this.system;
							let realH = height / (width / w);
							// this.system.h = realH.toFixed(0);
							this.dragBg.realH = realH.toFixed(0);
							this.getMode();
						},
						fail(res) {
							console.log("fail -> res", res, url);
						},
					});
				} else {
					this.dragBg.realH = 0;
				}
			},
			/**
			 * @description: 拖拽对象开始接触移动前
			 * @param {type}
			 * @return {type}
			 * @author:
			 */
			handleTouchStart(e) {
				// console.log(e);
				e.stopPropagation();
				e.preventDefault();
				var self = this;
				for (let i = 0; i < this.dragList.length; i++) {
					// 找到点击的
					this.dragList[i].active = false;
					if (e.currentTarget.dataset.id == this.dragList[i].id) {
						this.index = i; // 下标索引
						this.dragList[this.index].active = true; // 当前选中
					}
				}
				// 移动前点击的位置
				this.beforeMove = {
					x: e.touches[0].clientX,
					y: e.touches[0].clientY,
				};
			},
			handleClickStart(e, id) {
				for (let p of this.dragList) {
					if (p.id === id) {
						p.active = true;
					}
				}
			},
			handleTouchEnd(e) {
				e.preventDefault();
				// #ifdef H5
				// document.body.style.height = "auto";
				// document.body.style.overflow = "auto";
				// #endif
			},
			async getMode() {
				if (this.dragBg.realH >= this.system.h) {
					this.mode = "widthFix";
				} else {
					this.mode = !this.dragBg.cover ? "widthFix" : "";
				}
			},
			/**
			 * @description: 拖拽对象接触移动时
			 * @param {type}
			 * @return {type}
			 * @author:
			 */
			async handleTouchMove(e) {
				e.preventDefault();
				// let reactRes = await this.getRect('.bg-img');
				// if (reactRes.height >= this.system.h) {
				// #ifdef H5
				document.body.style.height = "100vh";
				document.body.style.overflow = "hidden";
				// #endif
				// }
				//移动时
				this.afterMove = {
					x: e.touches[0].clientX,
					y: e.touches[0].clientY,
				};
				//改动值赋值给当前原生属性
				this.dragList[this.index].left += this.afterMove.x - this.beforeMove.x; // x方向
				this.dragList[this.index].top += this.afterMove.y - this.beforeMove.y; // y方向

				// 新的位置复制为移动前的位置
				this.beforeMove = {
					x: e.touches[0].clientX,
					y: e.touches[0].clientY,
				};
			},
			/**
			 * @description: 缩放按钮开始接触移动前
			 * @param {type}
			 * @return {type}
			 * @author:
			 */
			handleScaleStart(e) {
				e.preventDefault();
				var self = this;
				for (let i = 0; i < this.dragList.length; i++) {
					// 找到点击的
					this.dragList[i].active = false;
					if (e.currentTarget.dataset.id == this.dragList[i].id) {
						this.index = i; // 下标索引
						this.dragList[this.index].active = true; // 当前选中
					}
				}
				// 移动前点击的位置
				this.beforeMove = {
					x: e.touches[0].clientX,
					y: e.touches[0].clientY,
				};
			},
			/**
			 * @description: 缩放按钮接触移动时
			 * @param {type}
			 * @return {type}
			 * @author:
			 */
			async handleScaleMove(e) {
				e.preventDefault();
				// let reactRes = await this.getRect('.bg-img');
				// if (reactRes.height >= this.system.h) {
				// #ifdef H5
				document.body.style.height = "100vh";
				document.body.style.overflow = "hidden";
				// #endif
				// }
				//移动时
				this.afterMove = {
					x: e.touches[0].clientX,
					y: e.touches[0].clientY,
				};
				this.dragList[this.index].width = this.dragList[this.index].width - 0;
				this.dragList[this.index].height = this.dragList[this.index].height - 0;
				//改动值赋值给当前原生属性
				this.dragList[this.index].width += this.afterMove.x - this.beforeMove.x; // x方向
				this.dragList[this.index].height += this.afterMove.y - this.beforeMove.y; // y方向
				this.dragList[this.index].width =
					this.dragList[this.index].width.toFixed(0);
				this.dragList[this.index].height =
					this.dragList[this.index].height.toFixed(0);
				// 新的位置复制为移动前的位置
				this.beforeMove = {
					x: e.touches[0].clientX,
					y: e.touches[0].clientY,
				};
			},
			getRect(selector, all) {
				return new Promise((resolve) => {
					uni
						.createSelectorQuery()
						.in(this)[all ? "selectAll" : "select"](selector)
						.boundingClientRect((rect) => {
							if (all && Array.isArray(rect) && rect.length) {
								resolve(rect);
							}
							if (!all && rect) {
								resolve(rect);
							}
							if (!rect) {
								resolve({
									height: 0,
								});
							}
						})
						.exec();
				});
			},
			/**
			 * @description: 删除拖拽元素
			 * @param {type}
			 * @return {type}
			 * @author:
			 */
			handleDel(i) {
				this.dragList.splice(i, 1);
			},
			/**
			 * @description: 编辑文本
			 * @param {type}
			 * @return {type}
			 * @author:
			 */
			handleEdit(item, i) {
				this.currentIndex = i;
				item.zIndex = i + 1;
				this.isEdit = true;
				if (item.type === "shape") {
					this.shapeData = item;
					// this.$refs.shape.show = true;
					this.shapeShow = true;
				} else if (item.type === "text") {
					this.fontShow = true;
					this.font = item;
					this.$refs.font.show = true;
				} else {
					this.imgObjData = item;
					this.$refs.imgObj.show = true;
				}
			},
			/**
			 * @description: 获取角度
			 * @param {type}
			 * @return {type}
			 * @author:
			 */
			countDeg(cx, cy, pointer_x, pointer_y) {
				var ox = pointer_x - cx;
				var oy = pointer_y - cy;
				var to = Math.abs(ox / oy);
				var angle = (Math.atan(to) / (2 * Math.PI)) * 360; //鼠标相对于旋转中心的角度
				if (ox < 0 && oy < 0) {
					//相对在左上角，第四象限，js中坐标系是从左上角开始的，这里的象限是正常坐标系
					angle = -angle;
				} else if (ox <= 0 && oy >= 0) {
					//左下角,3象限
					angle = -(180 - angle);
				} else if (ox > 0 && oy < 0) {
					//右上角，1象限
					angle = angle;
				} else if (ox > 0 && oy > 0) {
					//右下角，2象限
					angle = 180 - angle;
				}
				return angle;
			},
			async download(blob, fileName) {
				await window.reactNativeDownloadBlobUrl(
					URL.createObjectURL(blob),
					fileName
				);
			},
			/**
			 * @description: 生成海报
			 * @author:
			 */
			async creatPoster(type) {
				if (type === "同步") {
					window.ReactNativeWebView.postMessage("loading");
					this.saveStatus = true;
					for (let p of this.dragList) {
						if (p.active) {
							p.active = false;
						}
					}
					this.$nextTick(() => {
						const content = document.getElementById("content");
						html2canvas(content).then((value) => {
							value.toBlob((blob) => {
								this.saveStatus = false;
								const fileName = new Date().valueOf();
								if (window.platform === 'android') {
									this.download(blob, fileName).then(() => {
										window.ReactNativeWebView.postMessage(
											"同步" + fileName +
											`.${blob.type.split("/")[1]}`
										);
									});
								} else {

								}
							});
						});
					});
				}

				// console.dir(content);

				// this.canvasShow = true;
				// let reactRes = await this.getRect(".bg-img");
				// if (this.system.h < reactRes.height) {
				//   this.system.h = reactRes.height;
				// }
				// uni.showLoading({
				//   title: "生成海报中...",
				// });
				// const ctx = wx.createCanvasContext("myCanvas", this);
				// ctx.draw(); //清空之前的海报
				// // 根据设备屏幕大小和距离屏幕上下左右距离，及圆角绘制背景
				// let dragBg = this.dragBg;
				// if (this.dragBg.url) {
				//   this.dragBg.width = this.system.w;
				//   this.dragBg.height = this.system.h;
				//   if (!this.dragBg.cover) {
				//     this.dragBg.height = reactRes.height;
				//   }
				//   await drawSquarePic(
				//     ctx,
				//     dragBg.left,
				//     dragBg.top,
				//     dragBg.width,
				//     dragBg.height,
				//     dragBg.radius,
				//     dragBg.url,
				//     dragBg.color,
				//     dragBg.bgColor,
				//     dragBg.rotate,
				//     0,
				//     this.system
				//   );
				// } else {
				//   await drawSquarePic(
				//     ctx,
				//     0,
				//     0,
				//     this.system.w,
				//     this.system.h,
				//     0,
				//     dragBg.url,
				//     dragBg.color,
				//     dragBg.bgColor
				//   );
				// }
				// for (let i = 0; i < this.dragList.length; i++) {
				//   const element = this.dragList[i];
				//   if (element.type === "img" || element.type === "shape") {
				//     await drawSquarePic(
				//       ctx,
				//       element.left,
				//       element.top,
				//       element.width,
				//       element.height,
				//       element.radius,
				//       element.url,
				//       element.color || element.borderColor,
				//       element.backgroundColor,
				//       element.rotate,
				//       element.borderWidth
				//     );
				//   }
				//   if (element.type === "text") {
				//     console.log("creatPoster -> element", element);
				//     await drawTextReturnH(
				//       ctx,
				//       element.text,
				//       element.left,
				//       element.top,
				//       element.width,
				//       element.height,
				//       element.fontSize,
				//       element.color,
				//       element.textAlign,
				//       element.fontWeight,
				//       element.rotate
				//     );
				//   }
				// }
				// setTimeout(() => {
				//   this.handleSaveCanvasImage();
				// }, 500);
				// // wx.hideLoading();
			},
			onFileDownload(blob, fileName) {
			//	const a = document.createElement('a')
			//	a.href = URL.createObjectURL(blob)
			//	a.download = fileName + `.${blob.type.split("/")[1]}`
			//	a.click()
				var reader=new FileReader()
				reader.onload = function(event) {
				    var base64String = event.target.result; // 获取文件的 base64 编码
					window.ReactNativeWebView.postMessage(base64String);
				  };
				reader.readAsDataURL(blob)
			},
			/**
			 * @description: 保存到系统相册
			 * @param {type}
			 * @return {type}
			 * @author:
			 */
			handleSaveCanvasImage() {
				uni.showLoading({
					title: "保存中...",
				});
				let _this = this;
				// 把画布转化成临时文件
				// #ifndef MP-ALIPAY
				// 支付宝小程序外，其他都是用这个方法 canvasToTempFilePath
				uni.canvasToTempFilePath({
						x: 0,
						y: 0,
						width: this.system.w, // 画布的宽
						height: this.system.h, // 画布的高
						destWidth: this.system.w,
						destHeight: this.system.h,
						canvasId: "myCanvas",
						canvasId: "myCanvas",
						success: async (res) => {
							this.$emit("getImgUrl", {
								...res,
								dataSource: {
									dragBg: this.dragBg,
									dragList: this.dragList,
								},
							});
							// // 上传海报
							// let {fileID} = await upload(res.tempFilePath)
							// // 存储数据
							// await add({
							// 	createTime: Date.now(),
							// 	dragBg:_this.dragBg,
							// 	dragList:_this.dragList,
							// 	posterImgUrl:fileID
							// })
							//保存图片至相册
							// #ifndef H5
							// 除了h5以外的其他端
							_this.canvasToImgUrl = res.tempFilePath;
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success(res) {
									uni.hideLoading();
									uni.showToast({
										title: "图片保存成功，可以去分享啦~",
										duration: 2000,
										icon: "none",
									});
									// _this.handleCanvasCancel();
								},
								fail() {
									uni.showToast({
										title: "保存失败，稍后再试",
										duration: 2000,
										icon: "none",
									});
									uni.hideLoading();
								},
							});
							// #endif

							// #ifdef H5
							// h5的时候
							uni.showToast({
								title: "请长按保存",
								duration: 3000,
								icon: "none",
							});
							// _this.handleCanvasCancel();
							// 预览图片
							uni.previewImage({
								urls: [res.tempFilePath],
							});
							// #endif
						},
						fail(res) {
							console.log("fail -> res", res);
							uni.showToast({
								title: "保存失败，稍后再试",
								duration: 2000,
								icon: "none",
							});
							uni.hideLoading();
						},
					},
					this
				);
				// #endif
				// #ifdef MP-ALIPAY
				// 支付宝小程序条件下 toTempFilePath
				this.ctx.toTempFilePath({
						x: this.poster.x,
						y: this.poster.y,
						width: this.poster.w, // 画布的宽
						height: this.poster.h, // 画布的高
						destWidth: this.poster.w * 5,
						destHeight: this.poster.h * 5,
						success(res) {
							//保存图片至相册
							my.saveImage({
								url: res.apFilePath,
								showActionSheet: true,
								success(res) {
									uni.hideLoading();
									uni.showToast({
										title: "图片保存成功，可以去分享啦~",
										duration: 2000,
										icon: "none",
									});
									// _this.handleCanvasCancel();
								},
								fail() {
									uni.showToast({
										title: "保存失败，稍后再试",
										duration: 2000,
										icon: "none",
									});
									uni.hideLoading();
								},
							});
						},
						fail(res) {
							console.log("fail -> res", res);
							uni.showToast({
								title: "保存失败，稍后再试",
								duration: 2000,
								icon: "none",
							});
							uni.hideLoading();
						},
					},
					this
				);
				// #endif
			},
			handleClick() {
				for (let p of this.dragList) {
					p.active = false;
				}
			},
			/**
			 * @description: 取消海报
			 * @param {type}
			 * @return {type}
			 * @author:
			 */
			handleCanvasCancel() {
				this.canvasShow = false;
				this.dragList = [];
				this.dragBg.url = "";
				this.dragBg.bgColor = "#ffffff";
			},
			/**
			 * @description: 点击选择模板
			 * @param {type}
			 * @return {type}
			 * @author:
			 */
			/**
			 * @description: 选择文件
			 * @param {type}
			 * @return {type}
			 * @author:
			 */
			async handleChoose(type) {
				let res = await chooseImgUpload();
				const id = new Date().valueOf();
				if (window.platform === 'android') {
					this.download(res.file, id).then(() => {
						this.bgShow = false;
						let item = {
							id: id,
							type: "img",
							url: res.fileID,
							fileUrl: `file:///data/user/0/com.awesomeproject/files/${id}.${
		        res.file.type.split("/")[1]
		      }`,
							width: 100,
							height: 100,
							active: false,
							top: 40,
							left: 40,
							radius: 0,
							rotate: 0,
						};
						switch (type) {
							case "pic":
								this.dragList.push(item);
								this.dragList.map((item) => {
									item.active = false;
									if (item.id == id) {
										item.active = true;
									}
								});
								break;
							case "bg":
								this.dragBg.url = res.fileID;
								this.dragBg.fileUrl = `file:///data/user/0/com.awesomeproject/files/${id}.${
		          res.file.type.split("/")[1]
		        }`;

								this.$refs.Sbg.selectedIndex = 0;
								break;

							default:
								break;
						}
					});
				} else {
					this.onFileDownload(res.file, id)
					this.bgShow = false;
					let item = {
						id: id,
						type: "img",
						url: res.fileID,
						fileUrl: `file:///data/user/0/com.awesomeproject/files/${id}.${
					  res.file.type.split("/")[1]
					}`,
						width: 100,
						height: 100,
						active: false,
						top: 40,
						left: 40,
						radius: 0,
						rotate: 0,
					};
					switch (type) {
						case "pic":
							this.dragList.push(item);
							this.dragList.map((item) => {
								item.active = false;
								if (item.id == id) {
									item.active = true;
								}
							});
							break;
						case "bg":
							this.dragBg.url = res.fileID;
							this.dragBg.fileUrl = `file:///data/user/0/com.awesomeproject/files/${id}.${
					    res.file.type.split("/")[1]
					  }`;

							this.$refs.Sbg.selectedIndex = 0;
							break;

						default:
							break;
					}
				}
			},
			handleImgConfirm(e) {
				this.handleShapeConfirm(e);
			},
			handleShapeConfirm(e) {
				// console.log('<<<<yyds>>>>>', e.zIndex, this.currentIndex);
				e.zIndex = e.zIndex ? e.zIndex : 1;
				let list = this.dragList,
					currentItem = list.length ? list[this.currentIndex] : null,
					left = 40,
					id = Date.parse(new Date()),
					top = 40;
				if (this.isEdit)
					(top = currentItem ? currentItem.top : 40),
					(left = currentItem ? currentItem.left : 40),
					(id = currentItem ? currentItem.id : id);
				if (this.isEdit) {
					this.dragList[this.currentIndex] = {
						...this.dragList[this.currentIndex],
						...e,
					};
					this.dragList = this.changeArrIndex(
						this.dragList,
						this.currentIndex,
						e.zIndex - 1
					);
				} else {
					let item = {
						id: id,
						type: "shape",
						active: false,
						top: top,
						left: left,
						...e,
					};
					this.dragList.push(item);
				}
				this.dragList.map((item, index) => {
					if (!item.zIndex) item.zIndex = index + 1;
					item.active = false;
					if (item.id == id) {
						item.active = true;
					}
				});
				this.isEdit = false;
				this.shapeShow = false;
			},
			changeArrIndex(arr, startIndex, endIndex) {
				arr[startIndex] = arr.splice(endIndex, 1, arr[startIndex])[0];
				if (endIndex > arr.length - 1) arr.splice(startIndex, 1);
				const quickSort = (arr, key) => {
					let list = [];
					if (key) {
						list = arr.sort((a, b) => {
							if (key) {
								return a[key] - b[key];
							} else {
								return a - b;
							}
						});
					}
					return list;
				};
				return quickSort(arr, "zIndex");
			},
			/**
			 * @description: 确定文本字体
			 * @param {type}
			 * @return {type}
			 * @author:
			 */
			handleFontConfirm(font) {
				console.log("<<<<yyds>>>>>", font.zIndex, this.currentIndex);
				font.zIndex = font.zIndex ? font.zIndex : 1;
				let list = this.dragList,
					currentItem = list.length ? list[this.currentIndex] : null,
					left = 40,
					id = Date.parse(new Date()),
					top = 40;
				if (this.isEdit)
					(top = currentItem ? currentItem.top : 40),
					(left = currentItem ? currentItem.left : 40),
					(id = currentItem ? currentItem.id : id);
				this.fontShow = false;
				this.font = font;
				this.$refs.font.selectedIndex = 0;
				if (this.isEdit) {
					this.dragList[this.currentIndex].text = this.font.text;
					this.dragList[this.currentIndex].color = this.font.color;
					this.dragList[this.currentIndex].fontSize = this.font.fontSize;
					this.dragList[this.currentIndex].textDecoration =
						this.font.textDecoration;
					this.dragList[this.currentIndex].textAlign = this.font.textAlign;
					this.dragList[this.currentIndex].fontWeight = this.font.fontWeight;
					this.dragList[this.currentIndex].rotate = this.font.rotate;
					this.dragList[this.currentIndex].active = false;
					this.dragList[this.currentIndex].zIndex = font.zIndex;
					this.dragList[this.currentIndex].width = font.width;
					this.dragList[this.currentIndex].height = font.height;
					this.dragList[this.currentIndex].fontFamily = font.fontFamily;
					this.dragList = this.changeArrIndex(
						this.dragList,
						this.currentIndex,
						font.zIndex - 1
					);
				} else {
					let item = {
						id: id,
						type: "text",
						text: font.text,
						color: font.color,
						fontSize: font.fontSize,
						textDecoration: font.textDecoration,
						textAlign: font.textAlign,
						fontWeight: font.fontWeight,
						width: 200,
						height: 50,
						active: false,
						fontFamily: font.fontFamily,
						top: top,
						left: left,
						radius: 0,
						rotate: this.font.rotate,
					};
					this.dragList.push(item);
				}
				this.dragList.map((item, index) => {
					if (!item.zIndex) item.zIndex = index + 1;
					item.active = false;
					if (item.id == id) {
						item.active = true;
					}
				});
				this.isEdit = false;
			},
			/**
			 * @description: 字体大小
			 * @param {type}
			 * @return {type}
			 * @author:
			 */
			/**
			 * @description: 选择模板
			 * @param {type}
			 * @return {type}
			 * @author:
			 */
			saveTemplate() {
				localStorage.setItem(
					"dragData",
					JSON.stringify([
						...this.tempList,
						{
							name: this.textValue,
							id: new Date().valueOf(),
							value: {
								dragList: this.dragList,
								dragBg: this.dragBg,
							},
						},
					])
				);
				this.saveShow = false;
				this.textValue = "";
			},
			onConfirm(value) {
				this.dragList = value.dragList;
				this.dragBg = value.dragBg;
				this.sizeShow = false;
			},
		},
	};
</script>

<style lang="scss">
	.toolbar {
		background-color: #fff;
		height: 36px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 16px 24px;

		//   margin-top: 24px;
		.toolbar_item {
			display: flex;
			flex-direction: column;
			align-items: center;

			.toolbar_icon {
				width: 24px;
				height: 24px;
			}

			.toolbar_text {
				margin-top: 4px;
				font-size: 10px;
			}
		}
	}

	page {
		position: absolute;
		padding: 0;
		margin: 0;
		box-sizing: border-box;
		height: 100%;
		width: 100%;
	}

	.container {
		background-color: black;
		padding: 0 11px;
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.content {
		display: block;
		width: 100%;
		// height: calc(100% - 24px);
		background: #6739b6;
		margin: 12px 0;
		position: relative;

		.del-icon {
			position: fixed;
			right: 30rpx;
			top: 130rpx;
			width: 65rpx;
			height: 65rpx;
			z-index: 10;
		}

		.bg-icon {
			position: fixed;
			right: 30rpx;
			top: 110rpx;
			width: 70rpx;
			height: 70rpx;
			z-index: 10;
			// box-shadow: 0 0 10rpx #000;
			// border-radius: 15rpx;
		}

		.bg-img {
			width: 100%;
			position: absolute;
			height: 100%;
		}

		.drag-wrap {
			position: relative;

			.scale-icon {
				position: absolute;
				width: 40rpx;
				height: 40rpx;
				box-shadow: 0 0 10rpx #000;
				background-color: #fff;
				border-radius: 50%;
			}

			.scale-index {
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}

		.drag-item {
			position: absolute;
			display: block;
			overflow: hidden;
			word-break: break-all;
			line-height: 1;

			&.active {
				border: 7rpx dashed var(--border-color);
			}
		}

		.canvas {
			width: 100%;
			// height: 100%;
			// position: absolute;
			// top: 0;
			// left: 0;
			position: fixed;
			left: -1000000px;
			top: 0;
		}
	}

	.dialog-wrap {
		.choose-wrap {
			display: flex;
			flex-direction: row;
			justify-content: space-around;
		}

		.choose-item {
			display: flex;
			align-items: center;
			flex-direction: column;
			font-size: 28rpx;

			.img {
				width: 80rpx;
				height: 80rpx;
				margin-bottom: 20rpx;
			}
		}

		textarea {
			width: 100%;
		}

		.template-wrap {
			height: 500rpx;
			overflow: scroll;

			.template-item {
				width: 200rpx;
				margin: 30rpx;
			}
		}

		.editor-wrap {
			.color-wrap {
				display: flex;
				justify-items: center;
				line-height: 1;
				align-items: center;
				margin-bottom: 20rpx;
				font-size: $uni-font-size-sm;
				color: $uni-text-color-grey;

				.color-btn {
					width: 30px;
					height: 30px;
					margin-right: 20rpx;
					border: 1rpx solid $uni-border-color;
				}
			}
		}
	}

	.canvasToImgUrl {
		width: 100vw;
		// height: 100vh;
		position: relative;
	}
</style>